package com.nemodynamic.cattivial.facebook;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.android.Facebook;
import com.facebook.model.GraphUser;
import com.nemodynamic.cattivial.utils.Configuration;
import com.nemodynamic.cattivial.utils.ImageUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.ImageView;

public class AsyncTaskGetMyImage extends AsyncTask<Void, Void, Bitmap> {
	private Context context;
	private ImageView fbUserAvatar;
	private String user_ID;
	private String profileName;

	public AsyncTaskGetMyImage(Context context, Session fbsession, ImageView startButton) {
		this.fbUserAvatar = startButton;
		this.context = context;
	}

	@Override
	public Bitmap doInBackground(Void... params) {
		final Session session = Session.getActiveSession();
		if (session != null && session.isOpened()) {
			// If the session is open, make an API call to get user data
			// and define a new callback to handle the response
			Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
				@Override
				public void onCompleted(GraphUser user, Response response) {
					// If the response is successful
					if (session == Session.getActiveSession()) {
						if (user != null) {
							user_ID = user.getId();// user id
							profileName = user.getName();// user's profile name
						}
					}
				}
			});
			Request.executeAndWait(request);
		}
		URL fbAvatarUrl = null;
		Bitmap fbAvatarBitmap = null;
		try {
			fbAvatarUrl = new URL("http://graph.facebook.com/" + user_ID + "/picture?width=" + 300 + "&height=" + 300);
			fbAvatarBitmap = BitmapFactory.decodeStream(fbAvatarUrl.openConnection().getInputStream());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fbAvatarBitmap;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (result != null) {
			fbUserAvatar.setImageBitmap(ImageUtils.getStartButtonImages(result));
			saveUserData();
		}

	}

	private void saveUserData() {
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		SharedPreferences.Editor editor = preferences.edit();
		if (user_ID != null && profileName != null) {
			editor.putString(Configuration.USER_ID, user_ID);
			editor.putString(Configuration.USER_NAME, profileName);
			editor.commit();
		}
	}
}
